import { useState, useEffect, useCallback } from 'react'
import { chunk } from 'lodash-es'
// import { useTvWallStore } from '../store'

import { fetchGetAllTvwallStyles } from '@/api/manager/tvwall'
import Alert from '@/components/Alert'
import { boxPositionsEntity } from '@/api/manager/tvwall/interface'
export interface StyleInfoEntity {
	id: string
	name: string
	positions: Array<boxPositionsEntity>
}
export interface PageEntity {
	/**分页数据 */
	pageViewMap: Array<Array<StyleInfoEntity>>
	/**记录所有已选中的风格 */
	selectedStyleMap: any
	/**记录新选中的风格 */
	newSelectedStyleMap: Array<string>
	/**已选择通道所包含的风格 */
	selectedChnnlMap: any
	/**当前页*/
	nowPage: number
	/**总页数*/
	totalPage: number
	/**每页显示多少个风格 */
	numOfPage: number
	isMcc: boolean
	/**当前属于第几页 */
	curPageNo: 0
	/**接口返回的数据 */
	resPonseSource: Array<StyleInfoEntity>
	enableOk: boolean
	chnnlConflict: Array<string>
	tvwall_styleId_list: Array<string>

	/**模态框开启*/
	isOpen: boolean
}
export const useData = () => {
	const [pageData, setPageData] = useState<PageEntity>({
		pageViewMap: [],
		// styleMap: {},
		selectedStyleMap: {},
		newSelectedStyleMap: [],
		nowPage: 0, //当前页
		numOfPage: 4, //每页显示多少个风格
		selectedChnnlMap: {},
		isMcc: false,
		curPageNo: 0,
		totalPage: 0,
		resPonseSource: [],
		enableOk: false,
		chnnlConflict: [],
		tvwall_styleId_list: [],

		isOpen: false,
	})
	/**加载所有的电视墙风格*/
	const loadTVWallCfg = async () => {
		const res = await fetchGetAllTvwallStyles()
		if (res.success) {
			const { curPageNo, numOfPage } = pageData
			if (res?.data && res?.data?.length > 0) {
				let result = chunk(res.data, numOfPage) /**分好的数据数组[[],[]] */
				let _totalPage = result.length /**总页码*/
				updatePage({
					totalPage: _totalPage,
					nowPage: 0,
					pageViewMap: result,
					isMcc: true,
					isPrePageDisable: true,
					selectedStyleMap: {},
					selectedChnnlMap: {},
					resPonseSource: res.data,
				})
			} else {
				//无数据，判断是不是首页，否则继续加载
				if (curPageNo > 1) {
					updatePage({ curPageNo: 1 })
					loadTVWallCfg()
				}
			}
		} else {
			Alert(res.description || '')
		}
	}
	useEffect(() => {
		loadTVWallCfg()
	}, [])
	useEffect(() => {
		let result: { [key: string]: Array<string> } = {}
		const { resPonseSource, tvwall_styleId_list, newSelectedStyleMap } = pageData
		// 此处主要就是将例如3-1设备id加通道id 电视墙id
		// {
		// 	"3-1": ["XXXXXX", "XXXXX"],
		// 	"3-2": ["XXXXXX", "XXXXX"]
		// }
		resPonseSource.forEach((item) => {
			const _id = item.id /**风格id */
			if (tvwall_styleId_list.includes(_id) || newSelectedStyleMap.includes(_id)) {
				for (let k = 0; k < item.positions.length; k++) {
					let current = item.positions[k]
					let key_string = current.hdu_id /**设置id加通道id */
					if (!key_string) {
						continue
					}
					if (!result[key_string]) {
						result[key_string] = [_id]
					}
					if (!result[key_string].includes(_id)) {
						result[key_string].push(_id)
					}
				}
			}
		})
		updatePage({ enableOk: true })
		/**下面就是判断冲突比如设备 3-1 被多个电视墙风格选用,而且这些风格还被勾选*/
		let chnnlConflict = []
		for (let ChnnlInfo in result) {
			if (result[ChnnlInfo].length > 1) {
				updatePage({ enableOk: false })
				chnnlConflict.push(...result[ChnnlInfo])
			}
		}
		updatePage({ chnnlConflict: chnnlConflict })
	}, [pageData.resPonseSource, pageData.tvwall_styleId_list, pageData.newSelectedStyleMap])
	/**更新页面数据 */
	const updatePage = useCallback(
		(param) => {
			const changePageParam = Object.assign(pageData, param)
			setPageData({ ...changePageParam })
		},
		[pageData]
	)
	/**点击视图 */
	const handleClickView = (id: string) => {
		const { tvwall_styleId_list, newSelectedStyleMap: result } = pageData
		if (tvwall_styleId_list.includes(id)) {
			return
		}
		var _result = []
		if (result.includes(id)) {
			//取消选中
			for (var i = 0; i < result.length; i++) {
				if (id !== result[i]) {
					_result.push(result[i])
				}
			}
		} else {
			//新增进入
			_result.push(...result, id)
		}
		updatePage({ newSelectedStyleMap: _result })
	}
	return {
		pageData,
		updatePage,
		/**点击风格视图 */
		handleClickView,
	}
}
